package operatore;

import java.io.IOException;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entityBean.Operatore;

import sessionBean.GestoreOpBTPRemote;
import sessionBean.InfoOpCtrlRemote;

/**
 * Servlet implementation class ModificaDatiServlet
 */
public class ModificaDatiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ModificaDatiServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			processaRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			processaRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private InfoOpCtrlRemote getInfoOpCtrl() throws NamingException {

		Properties p = new Properties();
		p.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
		p.setProperty("java.naming.provider.url", "localhost:1099");
		p.setProperty("java.naming.url.pkgs", "org.jboss.naming");

		Object obj = new InitialContext(p).lookup("InfoOpCtrl/remote");

		return (InfoOpCtrlRemote)PortableRemoteObject.narrow(obj, InfoOpCtrlRemote.class);

	}

	private void processaRichiesta(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {

		String from = request.getParameter("from");
		String operatore = request.getParameter("operatore");

		if(from.equals("operatore")) {

			InfoOpCtrlRemote gestore = getInfoOpCtrl();
			
			Operatore o = gestore.getInfo(operatore);
			
			//Ora ho le informazioni dell'operatore e mostro la pagina di modifica
			//mandando le info dell'operatore alla jsp
			response.sendRedirect("ModInfoOp.jsp");

		}
		
		else {
			
			InfoOpCtrlRemote gestore = getInfoOpCtrl();
			
			String nuovoCod = request.getParameter("codice");
			String password = request.getParameter("password");
			
			Operatore o = gestore.modifica(operatore, nuovoCod, password);
			
		}

	}

}
